import React, { useCallback, useState, useEffect, forwardRef, useImperativeHandle, useRef } from 'react';
import {
  addEdge,
  Background,
  Controls,
  ReactFlow,
  ReactFlowProvider,
  useNodesState,
  useEdgesState,
  useReactFlow,
} from '@xyflow/react';
import { ConfigProvider } from 'antd';

import nodeTypes from '../nodeComponents';
import PropertiesPanel from '../PropertiesPanel';
import Sidebar from '../Sidebar';
import { createId } from '../../utils/util';
import '@xyflow/react/dist/style.css';
import './overviewReactflow.css';

import {
  initialNodes,
  initialEdges,
} from './initial-elements';


const AiWorkflow = forwardRef((props, ref) => {

  // 初始画布数据
  const [nodes, setNodes, onNodesChange] = useNodesState([]);
  const [edges, setEdges, onEdgesChange] = useEdgesState([]);

  const [currentNode, setCurrentNode] = useState();

  const { screenToFlowPosition } = useReactFlow();

  useEffect(() => {

    // data中的事件
    const onChange = (event) => {
      console.log("data中的事件")
      console.log(event)
      setNodes((nds) =>
        nds.map((node) => {

          if (node.type == 'startEvent') {

            console.log(node.type)
            console.log(node.data)

            return {
              ...node,
              data: {
                prologue: "1222",
                ...node.data,
              },
            };
          }
          return {
            ...node,
            data: {
              ...node.data,
            },
          };
        }),
      );
    }

    // 为节点添加事件
    let newInitialNodes = initialNodes?.map((node) => {
      console.log(node.data)

      return {
        ...node,
        data: {
          onChange: onChange,
          ...node.data,
        },
      };
    })
    // 根据数据初始化节点，实际从服务端获取
    setNodes(newInitialNodes)
    setEdges(initialEdges)
  }, []);

  const onConnect = useCallback(
    (connection) => setEdges((eds) => addEdge(connection, eds)),
    [setEdges],
  );

  const [reactFlowInstance, setReactFlowInstance] = useState(null);

  const [nodeProperties, setNodeProperties] = useState({});

  const onDragOver = useCallback((event) => {
    event.preventDefault();
    event.dataTransfer.dropEffect = 'move';
  }, []);

  const onDrop = useCallback(
    (event) => {
      event.preventDefault();

      const type = event.dataTransfer.getData('nodeType');

      // check if the dropped element is valid
      if (typeof type === 'undefined' || !type) {
        return;
      }

      const position = screenToFlowPosition({
        x: event.clientX,
        y: event.clientY,
      });

      const newNode = {
        id: createId(),
        type,
        position,
        data: { label: `${type} node` },
      };

      console.log(newNode);
      console.log(reactFlowInstance);
      // 获取画布对象
      console.log(reactFlowInstance.getNodes());
      setNodes((nds) => nds.concat(newNode));
    },
    [reactFlowInstance],
  );

  // we are using a bit of a shortcut here to adjust the edge type
  // this could also be done with a custom edge for example
  const edgesWithUpdatedTypes = edges.map((edge) => {
    if (edge.sourceHandle) {
      const edgeType = nodes.find((node) => node.type === 'custom').data
        .selects[edge.sourceHandle];
      edge.type = edgeType;
    }
    return edge;
  });

  // 这里可以添加你想要执行的代码，比如更新节点信息等
  const onNodeClick = (node, event) => {
    // 当前点击的节点
    console.log('Node clicked:', node);
    setCurrentNode(node)
  };

  // 定义子组件的方法
  useImperativeHandle(ref, () => ({
    saveModel: () => {
      // 当前点击的节点
      console.log('nodes:', nodes);
      console.log('edges:', edges);
    }
  }));

  return (
    <div className="dndflow">
      {/* 可以编排节点 */}
      <Sidebar />
      <div className="reactflow-wrapper" style={{ width: '100%', height: '600px' }}>
        {/* 画布 */}
        <ReactFlow
          nodes={nodes}
          edges={edgesWithUpdatedTypes}
          onNodesChange={onNodesChange}
          onEdgesChange={onEdgesChange}
          onConnect={onConnect}
          onInit={(instance) => {
            setReactFlowInstance(instance);
            // Set initial zoom and position
            instance.setViewport({ x: 0, y: 0, zoom: 0.8 });
          }}
          onDrop={onDrop}
          onDragOver={onDragOver}
          onNodeClick={onNodeClick}
          fitView
          fitViewOptions={{ padding: 0.2 }}
          defaultViewport={{ x: 0, y: 0, zoom: 0.8 }}
          style={{ background: '#f8f8f8' }}
          nodeTypes={nodeTypes}
        >
          <Controls />
          <Background color="#aaa" gap={16} />
        </ReactFlow>
      </div>
      {/* 属性面板: 聊天窗口或是节点属性配置 */}
      <PropertiesPanel nodeProperties={nodeProperties} />
    </div>
  );
});

export default forwardRef((props, ref) => {

  return (
    <ReactFlowProvider>
      <ConfigProvider
        theme={{
          token: {
            fontSize: 12,
          },
        }}
      >
        <AiWorkflow ref={ref} />
      </ConfigProvider>
    </ReactFlowProvider>
  );
})



